package com.example.server2;

import com.example.util.DBUtil;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.HashMap;

@WebServlet(name = "LoginServlet", value = "/LoginServlet")
public class LoginServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String account = request.getParameter("account");
        String password = request.getParameter("password");

        String resCode = "";
        String resMsg = "";
        Connection connection = DBUtil.getConnect();
        try{
            Statement statement = connection.createStatement();
            ResultSet result;
            String sqlQuery = "select * from " + DBUtil.TABLE_USER_PASSWORD + " where account='" + account + "'" +
                    " and  password='" + password + "'";
            result =  statement.executeQuery(sqlQuery);
            if (result.next()){//already has account x
                resCode = "200";
                resMsg = "登录成功";
            }else {
                resCode = "201";
                resMsg = "登录失败，密码不匹配或账号未注册";
            }
        }catch (Exception e){
            e.printStackTrace();
            resCode = "202";
            resMsg = "SQL错误 "+e.getMessage();
        }

        HashMap<String, String> map = new HashMap<>();
        map.put("resCode", resCode);
        map.put("resMsg", resMsg);

        response.setContentType("text/html;charset=utf-8"); // 设置响应报文的编码格式
        PrintWriter pw = response.getWriter(); // 获取 response 的输出流
        pw.println(map.toString()); // 通过输出流把业务逻辑的结果输出
        pw.flush();

    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request,response);
    }
}
